// reference https://github.com/scopsy/await-to-js

import type { IObject } from '@/types/customs';

/**
 * @template T
 * @template U
 * @param {Promise<T>} promise - The promise to handle.
 * @param {Object} [errorExt] - Additional error properties to extend the original error.
 * @returns {Promise<[U, undefined] | [null, T]>} A promise that resolves to a tuple indicating success or failure.
 */
export async function to<T, U = unknown>(
	promise: Promise<T>,
	errorExt?: IObject
): Promise<[U, undefined] | [null, T]> {
	try {
		const data = await promise;
		return [null, data];
	} catch (err) {
		if (errorExt) {
			const parsedError = Object.assign(
				{},
				typeof err === 'object' ? err : { msg: err },
				errorExt
			) as U & IObject;
			return [parsedError, undefined];
		}
		return [err as U, undefined];
	}
}
